package com.rocpenghua.ui;

import com.rocpenghua.service.AIService;
import com.rocpenghua.service.DeepSeekAIService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.ToolWindow;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class AIConsoleToolWindow {
    private final Project project;
    private final ToolWindow toolWindow;
    private final AIService aiService;
    private JPanel panel;
    private JTextArea chatArea;
    private JTextField inputField;
    private JButton sendButton;

    public AIConsoleToolWindow(Project project, ToolWindow toolWindow) {
        this.project = project;
        this.toolWindow = toolWindow;
        this.aiService = new DeepSeekAIService();

        panel = new JPanel(new BorderLayout());
        chatArea = new JTextArea();
        chatArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(chatArea);

        inputField = new JTextField();
        sendButton = new JButton("Send");

        JPanel inputPanel = new JPanel(new BorderLayout());
        inputPanel.add(inputField, BorderLayout.CENTER);
        inputPanel.add(sendButton, BorderLayout.EAST);

        panel.add(scrollPane, BorderLayout.CENTER);
        panel.add(inputPanel, BorderLayout.SOUTH);

        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMessage();
            }
        });

        inputField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMessage();
            }
        });
    }

    private void sendMessage() {
        String message = inputField.getText().trim();
        if (!message.isEmpty()) {
            chatArea.append("You: " + message + "\n");
            inputField.setText("");

            new Thread(() -> {
                String response = aiService.chat(message);
                SwingUtilities.invokeLater(() -> {
                    chatArea.append("AI: " + response + "\n\n");
                });
            }).start();
        }
    }

    public JPanel getContent() {
        return panel;
    }
}
